<template>
  <div class="fullMain">
    <x-header :left-options="{backText: '',showBack: back}">
      周报查看
      <!-- 修改删除的提示框 -->
      <div v-transfer-dom>
        <confirm
          v-model="isShowConfirm"
          :hide-on-blur="true"
          title="请选择操作"
          cancel-text="修改"
          confirm-text="退出"
          @on-cancel="modifyReview()">
        </confirm>
      </div>
    </x-header>
    <div style="height:20px"/>
    <div class="mainbBg">
      <div style="border: #f5f5f5 solid 2px;display: flex;margin-top: 0">
        <flexbox>
            <flexbox-item :span="3/8" >
                <popup-radio  class="popupradio-custom" :placeholder='placeholderOfGroup'
                v-model="group" :options="allGroups" @on-show="getAllGroups"></popup-radio>   
            </flexbox-item>
            <flexbox-item :span="2/8" >
                <popup-radio  class="popupradio-custom" :placeholder="placeholder_member" :options="groupMembers"
                v-model="member" @on-show="getGroupMembers"></popup-radio>   
            </flexbox-item>
            <flexbox-item >
                <calendar title='' :show-last-month=false :show-next-month=false 
                v-model="date" popup-header-title="请选择日期" ></calendar>
            </flexbox-item>
          </flexbox>
      </div>
      <br>
      <!--      循环展示结果-->
      <div class="groupDiv" v-if="this.result"
           style="height:calc(100% - 60px);margin-left:10px;margin-right:10px;overflow:auto;width:95%;">
        <div class="chatDiv" v-for="item in this.result" :key="item.reportId">
          <div style="display:inline-block; width:50px; height:auto; padding:0; 
          margin-left:5px; border:0px; background-color:rgb(237,237,237)">
            <img alt="" class="myHeadIcon" v-bind:src="item.avatar">
            <label>{{item.userName}}</label>
            <div style="font-size: xx-small">{{item.year}}年第{{item.week}}周</div>
          </div>

          <div style=" line-height:25px;width: 80%;float: right;" 
          @touchstart="touchstart(item)" @touchmove="touchmove()" @touchend="touchend()">
            <div :style="{background:(changeColor && item === temp?'#aeaeae':'white')}" >
              <span class="tag">本周已经完成</span><br>
              <div v-for="(itemOfDone,indexOfDone) in item.reportList" :key="indexOfDone">
                <p >
                  标题：{{itemOfDone.title}}<br>
                  用时：{{itemOfDone.hour}}小时<br>
                  工作内容：{{itemOfDone.workContent}}<br>
                  成效：{{itemOfDone.effect}}
                </p>
              </div>
              <span class="tag">下周计划完成</span><br>
              <div>
                <p>
                  {{item.nextWeekPlan}}</p>
              </div>
            </div>
          </div>
        </div>
      </div>

    </div>
  </div>
</template>

<script>
  import {PopupPicker, XHeader, Calendar, PopupRadio, 
    Confirm, TransferDomDirective as TransferDom,Flexbox, FlexboxItem} from 'vux'
  import {mapState} from 'Vuex'
  import {compareByProp} from 'utilMethods/sort'
  import group from 'api/group'
  import year from 'api/year'

  export default {
    name: 'S_view_annual_review',
    directives: {
      TransferDom
    },
    data () {
      return {
        // 长按事件相关
        temp: {},//长按选中的内容
        startX:'',
        startY:'',
        changeColor:false,//选中变色
        //下拉列表-群
        placeholderOfGroup: '请下拉选择要查看的群',//年报选择群的下拉列表
        group: '',//选择要显示年报的群，
        allGroups: [], // 存放所有群
        //下拉列表-成员
        placeholder_member: '成员',
        groupMembers: [], // 群成员
        member: '',//选择的成员
        //其它
        isShowConfirm: false,// 是否显示弹窗
        readonly: false,
        flagOfInit: true,//标志是否是初始化
        titleType: '',//动态标题
        result: [],//接收返回结果
        revType: '',//周期汇总类型
        //接口相关
        reportType: 0,
        date: '',//存放查询时的date
        editDate: {
          year: '2020',
          month: '003',
          flag: '',//用于设置为填写类型的标志，01-04为周报，05为月报，年报任意都可（因为年报 不查看本数据）
        },
        isMe:false,//只能是自己的周报才允许长按编辑
      }
    },
    computed: {
      ...mapState({
        userInfo: state => state.user.userInfo
      }),
      ...mapState(['reviewType', 'recordReviewItem']),
    },
    watch: {
      group (val) {
        this.checkAll()
      },
      member (val) {
        this.checkAll()
      },
      date (val) {
        this.checkAll()
      },
    },
    mounted () {
      this.init()
    },
    components: {
      PopupPicker,
      XHeader,
      Calendar,
      PopupRadio,
      Confirm,
      Flexbox, 
      FlexboxItem
    },
    methods: {
      init(){
        this.date = this.setToday()
        this.getAllGroups()
        this.checkAll()
      },
      back () {
        this.$router.go(-1)
      },
      setToday () {
        let myDate = new Date()
        let cmonth = myDate.getMonth() + 1
        let day = myDate.getDate()
        let hour = myDate.getHours()
        if (cmonth < 10) cmonth = '0' + cmonth
        if (day < 10) day = '0' + day
        return myDate.getFullYear() + '-' + cmonth + '-' + day
      },
      // 获取查询结果
      async checkAll () {
        if (this.member == '') {
          try {
            const temp = await year.getWeekReportRecent({
              date: this.date,
              groupId: this.group
            })
            if (temp.code === 1) {
              this.result = temp.data
            }else{
                this.result=''
            }
          } catch (err) {
            console.log('ERROR' + err)
          }
        } else {
          try {
            const temp = await year.getPersonWeekReport({
              date: this.date,
              userId: this.member
            })
            if (temp.code === 1) {
              //将code键值对删除，否则遍历的时候会将code也渲染上去，会多出一个没有内容没有头像的itme框；
              // 若将temp.data赋值给this.result，会遍历data，渲染出9个没有内容没有头像的itme框（因为item下有9的属性）
              delete temp.code
              this.result = temp
            }else{
                this.result=''
            }
          } catch (err) {
            console.log('ERROR' + err)
          }
        }

      },
      modifyReview () {
        this.$router.push({name: 'S_week_review',params:{modifyContent:this.temp}})
      },
      // 获取我加入的所有群
      async getAllGroups () {
        this.allGroups.length = 0
        const result = await group.getGroupsBeIn()
        if (result.code === 0) {
          this.showAlert('查询失败，请重试。')
        } else if (result.data.length === 0) {
          // this.showAlert('您暂时没有创建任何群')
        } else {
          let key, value
          result.data.forEach(element => {
            key = element.groupId
            value = element.detail.groupName
            this.allGroups.push({key, value})
          })
          // rock wang: 群名排序
          this.allGroups.sort(compareByProp('value'))
          //如果是初始化，就设置默认群组
          if (this.flagOfInit) {
            const max = this.allGroups.length - 1
            this.group = this.allGroups[max].key
            this.placeholderOfGroup = this.allGroups[max].value
            this.flagOfInit = false
          }
        }
        //初始化成员列表与日期列表
        this.groupMembers.length = 0
        this.member = ''
      },
      // 获取群内成员
      async getGroupMembers () {
        this.groupMembers.length = 0
        let tempMembers = []
        let key, value
        console.log('this.group::' + this.group)
        tempMembers = await group.getInfoOfMembers({groupId: this.group})
        console.log('tempMembers' + tempMembers)
        tempMembers.data.forEach(element => {
          key = element.userId
          value = element.detail.name
          this.groupMembers.push({key, value})
        })
      },
      touchstart (item) {
        if(item.userId === this.userInfo.userId){
          this.isMe = true
        }else{
          this.isMe = false
        }
        if(!this.isMe){return}
        this.temp = item
        this.changeColor = true
        this.timeOutEvent = 0
        this.timeOutEvent = setTimeout(this.longPress, 300)
        this.startX = event.changedTouches[0].pageX
        this.startY = event.changedTouches[0].pageY
      },
      touchmove () {
        if(!this.isMe){return}
        this.changeColor = false
        // event.preventDefault()
        var moveEndX = event.changedTouches[0].pageX
        var moveEndY = event.changedTouches[0].pageY
        var X = moveEndX - this.startX
        var Y = moveEndY - this.startY
        //允许小的滑动
        if ( Math.abs(X) > 2 && Math.abs(Y) > 2) {
          clearTimeout(this.timeOutEvent)// 清除定时器
          this.timeOutEvent = 0
        }
      },
      touchend () {
        if(!this.isMe){return}
        // event.preventDefault()
        this.changeColor = false
        if (this.timeOutEvent <= 500) {
          clearTimeout(this.timeOutEvent)
        }
      },
      longPress () {
        this.changeColor = false
        this.timeOutEvent = 0
        this.isShowConfirm = true
      }

    },
  }
</script>
<style lang="less" scoped>
  .myHeadIcon {
    display: inline-block;
    width: 50px;
    height: 50px;
    margin-top: 5px;
  }

  p {
    margin-top: 2px;
    margin-bottom: 2px;
  }

  *{
    -webkit-touch-callout:none;
    -webkit-user-select:none; 
    -khtml-user-select:none;
    -moz-user-select:none;
    -ms-user-select:none;
    user-select:none;
  }
  input ,textarea{
    -webkit-user-select:auto;
  }

</style>
